package com.feihong.yw189.paidan.fragment.jiedan;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;

import com.feihong.yw189.R;
import com.feihong.yw189.app.App;
import com.feihong.yw189.bluetooth.utils.util.ToastUtils;
import com.feihong.yw189.fragment.base.BaseFragment;
import com.feihong.yw189.listener.http.RequestCallBack;
import com.feihong.yw189.paidan.activity.DispatchActivity;
import com.feihong.yw189.paidan.adapter.DispatchListAdapter;
import com.feihong.yw189.paidan.adapter.JieDanOrderAdapter;
import com.feihong.yw189.paidan.bean.PaiDanOrder;
import com.feihong.yw189.paidan.inter.LiuDanListener;
import com.feihong.yw189.paidan.inter.RefOrderListListener;
import com.feihong.yw189.paidan.tools.RefReshToken;
import com.google.gson.Gson;
import com.holenzhou.pullrecyclerview.PullRecyclerView;

import org.xutils.common.Callback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * 订单页基类(公共方法)
 * 张鹏
 */
@RuntimePermissions
public class BaseList extends BaseFragment {
    private EditText ed_search;
    private DispatchActivity mActivity;
    private DispatchListAdapter dispatchListAdapter;
    private PullRecyclerView lv_order;
    private String search = "";
    public View fragmentView = null;
    private ImageView iv_zwdd;
    private PaiDanOrder paiDanOrder;
    private LiuDanListener mLiuDanListener;
    private JieDanOrderAdapter mPaiDanOrderAdapter;

    public void setPaiDanOrderAdapter(JieDanOrderAdapter mPaiDanOrderAdapter) {
        this.mPaiDanOrderAdapter = mPaiDanOrderAdapter;
    }

    public void setLiuDanListener(LiuDanListener mLiuDanListener) {
        this.mLiuDanListener = mLiuDanListener;
    }

    public static BaseList newInstance(String tabName) {
        BaseList rechargeFragment = new BaseList();
        return rechargeFragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        fragmentView = inflater.inflate(R.layout.item_pd_home, container, false);
        return fragmentView;

    }

    @Override
    protected void setTheme() {
        isDrakFont = false;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = (DispatchActivity) getActivity();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        ed_search.setText("");
        bindData();
    }

    private int orderType = 0;

    public void setOrderType(int orderType) {
        this.orderType = orderType;
    }

    /**
     * 初始化布局
     */
    @Override
    public void initView() {
        iv_zwdd = fragmentView.findViewById(R.id.iv_zwdd);
        ed_search = fragmentView.findViewById(R.id.ed_search);
        lv_order = fragmentView.findViewById(R.id.pull_recycler_view);
        // 做出搜索
        dispatchListAdapter = new DispatchListAdapter(_mActivity, new RefOrderListListener() {
            @Override
            public void onRefreshOrder() {

            }
        });
        // 设置权限监听
        dispatchListAdapter.setItemSelectListener(num -> {
            mTelNum = num;
            BaseListPermissionsDispatcher.needpermissionWithCheck(BaseList.this);
        });
        // 设置数据适配器
        lv_order.setAdapter(dispatchListAdapter);
        // 设置下拉刷新的旋转圆圈的颜色
        lv_order.setColorSchemeResources(R.color.orange);
        // 开启下拉刷新，默认即为true，可不用设置
        lv_order.enablePullRefresh(true);
        // 开启数据全部加载完成时的底部提示，默认为false
        lv_order.enableLoadDoneTip(true, R.string.load_done_tip);
        lv_order.enableLoadMore(false);

//        iv_zwdd.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                iv_zwdd.setVisibility(View.GONE);
//                lv_order.setVisibility(View.VISIBLE);
//                lv_order.autoRefresh();
//            }
//        });


        lv_order.setOnRecyclerRefreshListener(new PullRecyclerView.OnRecyclerRefreshListener() {
            @Override
            public void onPullRefresh() {
                ed_search.setText("");
                dispatchListAdapter.clear();
//                lv_order.enableLoadMore(true);
                getData("");
            }

            @Override
            public void onLoadMore() {
//                ed_search.setText("");
//                getData("");
            }
        });

        // 监听软键盘回车事件
        ed_search.setOnEditorActionListener((v, actionId, event) -> {

            if (actionId == EditorInfo.IME_ACTION_SEND
                    || actionId == EditorInfo.IME_ACTION_DONE
                    || actionId == EditorInfo.IME_ACTION_NONE
                    || actionId == EditorInfo.IME_ACTION_GO
                    || actionId == EditorInfo.IME_ACTION_SEARCH
                    || actionId == EditorInfo.IME_ACTION_NEXT
                    || (event != null && KeyEvent.KEYCODE_ENTER
                    == event.getKeyCode() && KeyEvent.ACTION_DOWN
                    == event.getAction())) {
                closeInputMethod(ed_search);
                //处理事件
                search = ed_search.getText().toString().trim();
                dispatchListAdapter.clear();
                getData(search);
            }
            return true;
        });
    }

    @Override
    public void bindData() {
        getData("");
    }

    private String mTelNum = "";

    private HashMap<String, String> numMap = new HashMap<>();

    List<PaiDanOrder.DataBeanX.OrderItemBean> data = new ArrayList<>();// 全部数据
    List<PaiDanOrder.DataBeanX.OrderItemBean> liuDanData = new ArrayList<>();// 留单
    List<PaiDanOrder.DataBeanX.OrderItemBean> waitData = new ArrayList<>();// 待处理

    private void getData(String search) {
        App.getApp().getHttpTools().getPaiDanHome("list", search, new RequestCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                Log.e("项目异常", "------getData------" + result);
                if (_mActivity == null || _mActivity.isDestroyed() || _mActivity.isFinishing()
                        || fragmentIsOnDestory()) {
                    return;
                }
                if (lv_order != null) {
                    lv_order.postDelayed(() -> {
                        lv_order.stopRefresh();
                        lv_order.stopLoadMore();
                    }, 300);
                }
                try {
                    Gson gson = new Gson();
                    paiDanOrder = gson.fromJson(result, PaiDanOrder.class);
                    if (paiDanOrder == null) {
//                        lv_order.enableLoadMore(false);
                        iv_zwdd.setVisibility(View.VISIBLE);
//                        lv_order.setVisibility(View.GONE);
                        ToastUtils.showShortToast(mActivity, "暂无更多订单！");
                        return;
                    }
                    if (paiDanOrder.getStatus() == 1) {
                        String status = paiDanOrder.getData().getStatus() + "";
                        String today_order_count = paiDanOrder.getData().getToday_order_count() + "";// 今日接单
                        String order_count = paiDanOrder.getData().getOrder_count() + "";// 全部接单
                        mLiuDanListener.onBackData(status, today_order_count, order_count);

                        data = paiDanOrder.getData().getData();// 全部数据
                        liuDanData = new ArrayList<>();// 留单
                        waitData = new ArrayList<>();// 待处理

                        if (paiDanOrder.getData() != null && data.size() > 0) {
                            iv_zwdd.setVisibility(View.GONE);
//                            lv_order.setVisibility(View.VISIBLE);
                            for (int i = 0; i < data.size(); i++) {
                                String is_liudan = data.get(i).getIs_liudan();
                                if ("1".equals(is_liudan)) {
                                    liuDanData.add(data.get(i));
                                } else if ("2".equals(is_liudan)) {
                                    waitData.add(data.get(i));
                                }
                            }
                            numMap = new HashMap<>();
                            // 获取订单数并更新显示
                            String allorder = data.size() + "";
                            String liuDan = liuDanData.size() + "";
                            String waitOrder = waitData.size() + "";
                            allorder = "全部 (" + allorder + ")";
                            liuDan = "留单(" + liuDan + ")";
                            waitOrder = "待处理(" + waitOrder + ")";
                            mLiuDanListener.onBackNum(allorder, liuDan, waitOrder);

                            if (orderType == 0) {
                                dispatchListAdapter.addAll(data);
                            } else if (orderType == 1) {
                                if (liuDanData.size() > 0) {
                                    dispatchListAdapter.addAll(liuDanData);

                                } else {
                                    iv_zwdd.setVisibility(View.VISIBLE);
//                                    lv_order.setVisibility(View.GONE);
                                }
                            } else if (orderType == 2) {
                                if (waitData.size() > 0) {
                                    dispatchListAdapter.addAll(waitData);

                                } else {
                                    iv_zwdd.setVisibility(View.VISIBLE);
//                                    lv_order.setVisibility(View.GONE);
                                }
                            }
                            lv_order.setAdapter(dispatchListAdapter);
                        } else {
//                            lv_order.enableLoadMore(false);
                            iv_zwdd.setVisibility(View.VISIBLE);
//                            lv_order.setVisibility(View.GONE);
                            ToastUtils.showShortToast(mActivity, "暂无更多订单！");
                        }
                    } else if (paiDanOrder.getStatus() == 401) {
                        Boolean sucRef = RefReshToken.refshToken();
                        if (sucRef) {
                            getData(search);
                        } else {
                            RefReshToken.exitLogin();
                        }
                    } else {
                        iv_zwdd.setVisibility(View.VISIBLE);
//                        lv_order.setVisibility(View.GONE);
                        ToastUtils.showShortToast(mActivity, paiDanOrder.getInfo());

                        return;
                    }
                } catch (Exception e) {
                    iv_zwdd.setVisibility(View.VISIBLE);
//                    lv_order.setVisibility(View.GONE);
                    Log.e(TAG, "onSuccess: 出错错误:" + e.toString());
                    ToastUtils.showShortToast(mActivity, "数据解析错误");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e("项目异常", "------onError------" + ex.toString());
                if (_mActivity == null || _mActivity.isDestroyed() || _mActivity.isFinishing()
                        || fragmentIsOnDestory()) {
                    return;
                }
                if (lv_order != null) {
                    lv_order.postDelayed(() -> {
                        lv_order.stopLoadMore();
                        lv_order.stopRefresh();
                    }, 300);
                }
                iv_zwdd.setVisibility(View.VISIBLE);
//                lv_order.setVisibility(View.GONE);
                dispatchListAdapter.setData(new ArrayList<PaiDanOrder.DataBeanX.OrderItemBean>());
                ToastUtils.showShortToast(mActivity, "网络或服务器错误");
            }

            @Override
            public void onCancelled(Callback.CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }

        });
    }

    @NeedsPermission(Manifest.permission.CALL_PHONE)
    void needpermission() {
        if (!TextUtils.isEmpty(mTelNum)) {
            Uri uri = Uri.parse("tel:" + mTelNum);
            Intent intent = new Intent();
//                    intent.setAction(Intent.ACTION_DIAL); // 调用拨号盘
            intent.setAction(Intent.ACTION_CALL); // 调用拨号
            intent.setData(uri);
            startActivity(intent);

        }
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        BaseListPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale(Manifest.permission.CALL_PHONE)
    void showRational(final PermissionRequest request) {
        new AlertDialog.Builder(mActivity)
                .setPositiveButton("允许", (dialog, which) ->
                        request.proceed())
                .setNegativeButton("拒绝", (dialog, which) ->
                        request.cancel())
                .setCancelable(false)
                .setMessage("请允许获取打电话权限")
                .show();
    }

    @OnPermissionDenied(Manifest.permission.CALL_PHONE)
    void Denied() {
        ToastUtils.showShortToast(mActivity, "权限不足,您没有开启此应用的使用打电话权限。请到系统设置-->权限管理 开启打电话使用权限。如果您的手机上安装了第三方应用管家（360管家，腾讯管家等），请开启一下打电话权限！");
    }

    @OnNeverAskAgain(Manifest.permission.CALL_PHONE)
    void AskAgin() {
        ToastUtils.showShortToast(mActivity, "权限不足,您没有开启此应用的使用打电话权限。请到系统设置-->权限管理 开启打电话使用权限。如果您的手机上安装了第三方应用管家（360管家，腾讯管家等），请开启一下打电话权限！");
    }

    private void closeInputMethod(View view) {
        InputMethodManager imm = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
        boolean isOpen = imm.isActive();
        if (isOpen) {
            // imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);//没有显示则显示
            imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
}
